from typing import List
from neo4j.graph import Node, Relationship, Path
import logging
import re

def format_cypher_result(result: List) -> str:
    """格式化 Cypher 查询结果"""
    if not result:
        return "未找到相关信息"
        
    formatted = []
    nodes_info = []
    relationships_info = []
    documents_info = []
    
    for record in result:
        try:
            # 处理节点
            if 'n' in record:
                node = record['n']
                if isinstance(node, Node):
                    node_props = dict(node)
                    node_labels = list(node.labels)
                    if '__Entity__' in node_labels:
                        node_labels.remove('__Entity__')
                    node_str = f"节点: {node_props.get('id', 'N/A')} (类型: {', '.join(node_labels)})"
                    nodes_info.append(node_str)
                    logging.info(f"Found node: {node_str}")
            
            # 处理关系目标节点
            if 'm' in record:
                node = record['m']
                if isinstance(node, Node):
                    node_props = dict(node)
                    node_labels = list(node.labels)
                    if '__Entity__' in node_labels:
                        node_labels.remove('__Entity__')
                    node_str = f"节点: {node_props.get('id', 'N/A')} (类型: {', '.join(node_labels)})"
                    nodes_info.append(node_str)
                    logging.info(f"Found node: {node_str}")
            
            # 处理关系
            if 'r' in record and ('n' in record or 'm' in record):
                rel = record['r']
                if isinstance(rel, Relationship):
                    start_node = record.get('n') or rel.start_node
                    end_node = record.get('m') or rel.end_node
                    if isinstance(start_node, Node) and isinstance(end_node, Node):
                        start_props = dict(start_node)
                        end_props = dict(end_node)
                        rel_str = f"关系: {start_props.get('id', 'N/A')} -[{rel.type}]-> {end_props.get('id', 'N/A')}"
                        relationships_info.append(rel_str)
                        logging.info(f"Found relationship: {rel_str}")
            
            # 处理文档
            for doc_key in ['d', 'd2']:
                if doc_key in record:
                    doc = record[doc_key]
                    if isinstance(doc, Node) and 'Document' in doc.labels:
                        doc_props = dict(doc)
                        text = doc_props.get('text', '').replace('\u3000', ' ')
                        if text:
                            # 提取包含特定实体的相关内容
                            pattern = r'\[(.*?)\].*?(?=\[|$)'
                            matches = re.findall(pattern, text)
                            relevant_content = []
                            for match in matches:
                                if '.' in match:  # 包含属性描述
                                    content = match.strip()
                                    if content not in relevant_content:
                                        relevant_content.append(content)
                            
                            if relevant_content:
                                documents_info.extend(relevant_content)
                            else:
                                # 如果没有找到特定格式的内容，取一个合适的片段
                                summary = text[:200] + "..." if len(text) > 200 else text
                                if summary not in documents_info:
                                    documents_info.append(summary)
                                    
                            logging.info(f"Found document content: {relevant_content[:2]}")
                        
        except Exception as e:
            logging.error(f"Error formatting record: {e}")
            continue
    
    # 去重并组织结果
    unique_nodes = list(set(nodes_info))
    unique_relationships = list(set(relationships_info))
    unique_documents = list(set(documents_info))
    
    # 组织结果
    if unique_nodes:
        formatted.append("【节点信息】\n" + "\n".join(unique_nodes))
    
    if unique_relationships:
        formatted.append("【关系信息】\n" + "\n".join(unique_relationships))
    
    if unique_documents:
        formatted.append("【相关描述】\n" + "\n".join(
            [f"• {doc}" for doc in unique_documents]
        ))
    
    if not formatted:
        return "未找到相关信息"
        
    return "\n\n".join(formatted) 